package com.yungu.swift.admin.utils;

import com.yungu.swift.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * 三方互通的AES对称性加密
 */
@Slf4j
public class AESCipher {

    private static final String IV_STRING = "16-Bytes--String";

    private static final Base64.Decoder DECODER = Base64.getDecoder();
    private static final Base64.Encoder ENCODER = Base64.getEncoder();

    static String encryptAES(String content, String key) {
        if (StringUtils.isEmpty(content)) {
            return content;
        }
        try {
            byte[] byteContent = content.getBytes("UTF-8");
            byte[] enCodeFormat = key.getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] encryptedBytes = cipher.doFinal(byteContent);
            return ENCODER.encode(encryptedBytes).toString();
        } catch (Exception e) {
            log.error("AESCipher encryptAES error, content:{}", content, e);
        }
        return "";
    }

    static String decryptAES(String content, String key) {
        if (StringUtils.isEmpty(content)) {
            return content;
        }
        try {
            byte[] encryptedBytes = DECODER.decode(content);
            byte[] enCodeFormat = key.getBytes();
            SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
            byte[] result = cipher.doFinal(encryptedBytes);
            return new String(result, "UTF-8");
        } catch (Exception e) {
            log.error("AESCipher decryptAES error, content:{}", content, e);
        }
        return "";
    }

}
